package com.wzdigit.wms.wms.service.core;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Map.Entry;

@Component
public class WmsSpringUtil implements ApplicationContextAware {

	private ApplicationContext applicationContext;
	private BeanDefinitionRegistry beanDefinitionRegistry;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		if (this.applicationContext == null) {
			this.applicationContext = applicationContext;
			this.beanDefinitionRegistry = (DefaultListableBeanFactory) applicationContext
					.getAutowireCapableBeanFactory();
		}
	}

	// 获取applicationContext
	public ApplicationContext getApplicationContext() {
		return applicationContext;
	}

	// 通过name获取 Bean.
	public Object getBean(String name) {
		return getApplicationContext().getBean(name);
	}

	// 通过class获取Bean.
	public <T> T getBean(Class<T> clazz) {
		return getApplicationContext().getBean(clazz);
	}

	// 通过name,以及Clazz返回指定的Bean
	public <T> T getBean(String name, Class<T> clazz) {
		return getApplicationContext().getBean(name, clazz);
	}

	/**
	 * 注册bean
	 * 
	 * @param <T>
	 * 
	 */
	public <T> void registerBean(String className, Class<T> clazz, Map<String, Object> propertys) {
		BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(clazz);
		for (Entry<String, Object> entry : propertys.entrySet()) {
			beanDefinitionBuilder.addPropertyValue(entry.getKey(), entry.getValue());
		}
		BeanDefinition beanDefinition = beanDefinitionBuilder.getBeanDefinition();
		beanDefinitionRegistry.registerBeanDefinition(className, beanDefinition);
	}

	/**
	 * 移除bean
	 * 
	 * @param <T>
	 * @param beanId
	 */
	public <T> void unregisterBean(Class<T> className) {
		beanDefinitionRegistry.removeBeanDefinition(className.getName());
	}
}
